require 'set'

class PeopleController < ApplicationController
  layout 'main'
  
  before_filter :login_required
  
  filter_parameter_logging :person

  # GET /people/new
  # GET /people/new.xml
  def new
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @person }
    end
  end

  # POST /people
  # POST /people.xml
  def create
    @person = Person.new(params[:person])

    respond_to do |format|
      if @person.is_valid?
        criterias = @person.find_valid_criteria
        criteria_ids = criterias.collect { |criteria| criteria.id }
        
        unless criterias.empty?
          @rooms = Room.find(:all, :include => :criterias)
          @rooms.delete_if { |room| room.criteria_ids.inject(false) { |i,x| criteria_ids.include?(x) ? i : true } }
          @rooms.delete_if { |room| room.not_criteria_ids.inject(false) { |i,x| criteria_ids.include?(x) ? true : i } }
        else
          @rooms = Room.find(:all, :include => :criterias)
          @rooms.delete_if {|room| !room.criterias.empty?}
        end
        
        @rooms.delete_if {|room| room.occupied?}

        @sites = @rooms.collect { |room| room.site }.to_set
        
        format.html # create.html.erb
        format.xml  { render :xml => @person, :status => :created, :location => @person }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @person.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  def show
    redirect_to new_person_path
  end
end
